<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>提示词模板管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px 0;
            text-align: center;
            margin-bottom: 30px;
            border-radius: 10px;
        }
        
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .nav-tabs {
            display: flex;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .nav-tab {
            flex: 1;
            padding: 15px 20px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .nav-tab:hover {
            background: #f8f9fa;
        }
        
        .nav-tab.active {
            background: #667eea;
            color: white;
        }
        
        .tab-content {
            display: none;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .tab-content.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #555;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e1e5e9;
            border-radius: 6px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 150px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .template-list {
            display: grid;
            gap: 20px;
        }
        
        .template-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        
        .template-card:hover {
            transform: translateY(-5px);
        }
        
        .template-card h3 {
            color: #333;
            margin-bottom: 10px;
            font-size: 1.3rem;
        }
        
        .template-card .meta {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 15px;
        }
        
        .template-card .description {
            color: #555;
            margin-bottom: 15px;
            line-height: 1.5;
        }
        
        .template-card .actions {
            display: flex;
            gap: 10px;
        }
        
        .parameters-list {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            margin-top: 15px;
        }
        
        .parameter-item {
            background: white;
            border-radius: 6px;
            padding: 10px;
            margin-bottom: 10px;
            border-left: 4px solid #667eea;
        }
        
        .parameter-item:last-child {
            margin-bottom: 0;
        }
        
        .parameter-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .parameter-meta {
            font-size: 0.85rem;
            color: #666;
        }
        
        .render-result {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 20px;
            margin-top: 20px;
            border: 1px solid #e1e5e9;
        }
        
        .render-result h4 {
            margin-bottom: 10px;
            color: #333;
        }
        
        .render-result pre {
            background: white;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid #e1e5e9;
            overflow-x: auto;
            white-space: pre-wrap;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .stat-card .number {
            font-size: 2.5rem;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
        
        .stat-card .label {
            color: #666;
            font-size: 0.9rem;
        }
        
        .notification {
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 20px;
            display: none;
        }
        
        .notification.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .notification.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .notification.show {
            display: block;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        
        .parameter-config {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .parameter-config h4 {
            margin-bottom: 10px;
            color: #333;
        }
        
        .parameter-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .parameters-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        
        .parameters-table th,
        .parameters-table td {
            border: 1px solid #e1e5e9;
            padding: 10px;
            text-align: left;
        }
        
        .parameters-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #555;
        }
        
        .parameters-table tr:hover {
            background: #f8f9fa;
        }
        
        .parameter-actions {
            display: flex;
            gap: 5px;
        }
        
        .parameter-actions button {
            padding: 5px 10px;
            font-size: 0.85rem;
        }
        
        .thinking-config {
            background: #f0f8ff;
            border: 1px solid #b8daff;
            border-radius: 6px;
            padding: 15px;
            margin-top: 10px;
        }
        
        .thinking-config h4 {
            color: #004085;
            margin-bottom: 15px;
        }
        
        .thinking-config .form-group {
            margin-bottom: 15px;
        }
        
        .thinking-config label {
            color: #004085;
            font-weight: 600;
        }
        
        @media (max-width: 768px) {
            .parameter-row {
                grid-template-columns: 1fr;
            }
            
            .nav-tabs {
                flex-direction: column;
            }
            
            .header h1 {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>提示词模板管理系统</h1>
            <p>创建、管理和使用AI提示词模板</p>
        </div>
        
        <div class="nav-tabs">
            <button class="nav-tab active" onclick="showTab('templates')">模板列表</button>
            <button class="nav-tab" onclick="showTab('create')">创建模板</button>
            <button class="nav-tab" onclick="showTab('render')">渲染测试</button>
            <button class="nav-tab" onclick="showTab('stats')">使用统计</button>
        </div>
        
        <div class="notification" id="notification"></div>
        
        <!-- 模板列表 -->
        <div class="tab-content active" id="templates-tab">
            <h2>提示词模板列表</h2>
            <div class="template-list" id="template-list">
                <div class="loading">正在加载模板...</div>
            </div>
        </div>
        
        <!-- 创建模板 -->
        <div class="tab-content" id="create-tab">
            <h2>创建提示词模板</h2>
            <form id="create-template-form">
                <div class="form-group">
                    <label for="template-name">模板名称</label>
                    <input type="text" id="template-name" required placeholder="请输入模板名称">
                </div>
                
                <div class="form-group">
                    <label for="template-description">模板描述</label>
                    <textarea id="template-description" placeholder="请输入模板描述"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="template-category">分类</label>
                    <select id="template-category">
                        <option value="信访分析">信访分析</option>
                        <option value="情感分析">情感分析</option>
                        <option value="信息提取">信息提取</option>
                        <option value="文本生成">文本生成</option>
                        <option value="通用工具">通用工具</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="template-content">模板内容</label>
                    <textarea id="template-content" required placeholder="请输入模板内容，使用 {{parameter_name}} 作为参数占位符"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="template-format">输出格式</label>
                    <select id="template-format">
                        <option value="json">JSON</option>
                        <option value="text">纯文本</option>
                        <option value="markdown">Markdown</option>
                        <option value="html">HTML</option>
                    </select>
                </div>
                
                <!-- 深度思考配置 -->
                <div class="parameter-config">
                    <h4>深度思考配置</h4>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="enable-thinking" onchange="toggleThinkingConfig()"> 启用深度思考
                        </label>
                    </div>
                    <div id="thinking-config" style="display: none;">
                        <div class="form-group">
                            <label for="thinking-mode">思考模式</label>
                            <select id="thinking-mode">
                                <option value="auto">自动</option>
                                <option value="enabled">启用</option>
                                <option value="disabled">禁用</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="thinking-prompt">深度思考提示词</label>
                            <textarea id="thinking-prompt" rows="4" placeholder="请输入深度思考的提示词，可以使用 {参数名} 来引用参数值..."></textarea>
                            <small style="color: #666;">提示：您可以使用参数占位符，只有标记为"在深度思考中使用"的参数才会被传递到深度思考提示词中</small>
                        </div>
                    </div>
                </div>
                
                <!-- 参数配置 -->
                <div class="parameter-config">
                    <h4>参数配置</h4>
                    <div id="parameters-list">
                        <!-- 参数列表将在这里动态生成 -->
                    </div>
                    <button type="button" class="btn btn-secondary" onclick="addParameter()">添加参数</button>
                </div>
                
                <div style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary">创建模板</button>
                    <button type="button" class="btn btn-secondary" onclick="validateTemplate()">验证模板</button>
                </div>
            </form>
        </div>
        
        <!-- 渲染测试 -->
        <div class="tab-content" id="render-tab">
            <h2>渲染测试</h2>
            <div class="form-group">
                <label for="render-template">选择模板</label>
                <select id="render-template">
                    <option value="">请选择模板</option>
                </select>
            </div>
            
            <div id="render-parameters">
                <!-- 参数输入将在这里动态生成 -->
            </div>
            
            <div style="margin-top: 20px;">
                <button class="btn btn-primary" onclick="renderTemplate()">渲染提示词</button>
            </div>
            
            <div class="render-result" id="render-result" style="display: none;">
                <h4>渲染结果</h4>
                <pre id="rendered-content"></pre>
            </div>
        </div>
        
        <!-- 使用统计 -->
        <div class="tab-content" id="stats-tab">
            <h2>使用统计</h2>
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="number" id="total-templates">0</div>
                    <div class="label">总模板数</div>
                </div>
                <div class="stat-card">
                    <div class="number" id="total-usage">0</div>
                    <div class="label">总使用次数</div>
                </div>
                <div class="stat-card">
                    <div class="number" id="success-rate">0%</div>
                    <div class="label">成功率</div>
                </div>
                <div class="stat-card">
                    <div class="number" id="avg-time">0ms</div>
                    <div class="label">平均耗时</div>
                </div>
            </div>
            
            <div class="template-list" id="stats-templates">
                <div class="loading">正在加载统计数据...</div>
            </div>
        </div>
    </div>
    
    <script>
        // 全局变量
        let templates = [];
        let parameterCounter = 0;
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadTemplates();
            loadStats();
            
            // 绑定表单提交事件
            document.getElementById('create-template-form').addEventListener('submit', createTemplate);
        });
        
        // 显示标签页
        function showTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 移除所有标签的激活状态
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签内容
            document.getElementById(tabName + '-tab').classList.add('active');
            
            // 激活选中的标签
            event.target.classList.add('active');
        }
        
        // 显示通知
        function showNotification(message, type = 'success') {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = `notification ${type} show`;
            
            setTimeout(() => {
                notification.classList.remove('show');
            }, 3000);
        }
        
        // 加载模板列表
        async function loadTemplates() {
            try {
                const response = await fetch('/api/prompts/');
                const data = await response.json();
                
                if (data.code === 200) {
                    templates = data.data.items;
                    displayTemplates(templates);
                    updateTemplateSelect(templates);
                } else {
                    showNotification('加载模板失败: ' + data.message, 'error');
                }
            } catch (error) {
                showNotification('加载模板失败: ' + error.message, 'error');
            }
        }
        
        // 显示模板列表
        function displayTemplates(templates) {
            const container = document.getElementById('template-list');
            
            if (templates.length === 0) {
                container.innerHTML = '<div class="loading">暂无模板</div>';
                return;
            }
            
            container.innerHTML = templates.map(template => `
                <div class="template-card">
                    <h3>${template.name}</h3>
                    <div class="meta">
                        分类: ${template.category} | 
                        格式: ${template.output_format} | 
                        使用次数: ${template.usage_count || 0}
                    </div>
                    <div class="description">${template.description || '无描述'}</div>
                    <div class="actions">
                        <button class="btn btn-primary" onclick="editTemplate(${template.id})">编辑</button>
                        <button class="btn btn-success" onclick="duplicateTemplate(${template.id})">复制</button>
                        <button class="btn btn-danger" onclick="deleteTemplate(${template.id})">删除</button>
                    </div>
                    ${template.parameters && template.parameters.length > 0 ? `
                        <div class="parameters-list">
                            <h4>参数列表</h4>
                            ${template.parameters.map(param => `
                                <div class="parameter-item">
                                    <div class="parameter-name">${param.name}</div>
                                    <div class="parameter-meta">
                                        类型: ${param.param_type} | 
                                        ${param.is_required ? '必填' : '可选'} | 
                                        ${param.description || ''}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    ` : ''}
                </div>
            `).join('');
        }
        
        // 更新模板选择下拉框
        function updateTemplateSelect(templates) {
            const select = document.getElementById('render-template');
            select.innerHTML = '<option value="">请选择模板</option>' + 
                templates.map(template => 
                    `<option value="${template.id}">${template.name}</option>`
                ).join('');
        }
        
        // 切换深度思考配置显示
        function toggleThinkingConfig() {
            const enableThinking = document.getElementById('enable-thinking').checked;
            const thinkingConfig = document.getElementById('thinking-config');
            thinkingConfig.style.display = enableThinking ? 'block' : 'none';
        }
        
        // 添加参数配置
        function addParameter() {
            parameterCounter++;
            const container = document.getElementById('parameters-list');
            
            const paramHtml = `
                <div class="parameter-config" id="param-${parameterCounter}">
                    <h5 style="margin-bottom: 10px; color: #333;">参数 ${parameterCounter}</h5>
                    
                    <table class="parameters-table">
                        <tr>
                            <td style="width: 50%;">
                                <label>参数名称 *</label>
                                <input type="text" name="param_name" required placeholder="参数名" style="width: 100%; margin-top: 5px;">
                            </td>
                            <td style="width: 50%;">
                                <label>参数类型</label>
                                <select name="param_type" style="width: 100%; margin-top: 5px;">
                                    <option value="string">字符串</option>
                                    <option value="integer">整数</option>
                                    <option value="float">浮点数</option>
                                    <option value="boolean">布尔值</option>
                                    <option value="array">数组</option>
                                    <option value="object">对象</option>
                                    <option value="date">日期</option>
                                    <option value="datetime">日期时间</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label>显示名称</label>
                                <input type="text" name="param_display" placeholder="显示名称" style="width: 100%; margin-top: 5px;">
                            </td>
                            <td>
                                <label>是否必填</label>
                                <select name="param_required" style="width: 100%; margin-top: 5px;">
                                    <option value="false">可选</option>
                                    <option value="true">必填</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <label>描述</label>
                                <input type="text" name="param_description" placeholder="参数描述" style="width: 100%; margin-top: 5px;">
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <label>默认值</label>
                                <input type="text" name="param_default" placeholder="默认值" style="width: 100%; margin-top: 5px;">
                            </td>
                            <td>
                                <label>UI组件</label>
                                <select name="param_ui" style="width: 100%; margin-top: 5px;">
                                    <option value="input">输入框</option>
                                    <option value="textarea">文本域</option>
                                    <option value="select">下拉选择</option>
                                    <option value="checkbox">复选框</option>
                                    <option value="radio">单选框</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <label>
                                    <input type="checkbox" name="param_thinking" style="margin-right: 5px;">
                                    在深度思考中使用此参数
                                </label>
                            </td>
                        </tr>
                    </table>
                    
                    <div style="margin-top: 15px; text-align: center;">
                        <button type="button" class="btn btn-danger" onclick="removeParameter('param-${parameterCounter}')">删除参数</button>
                    </div>
                </div>
            `;
            
            container.insertAdjacentHTML('beforeend', paramHtml);
        }
        
        // 删除参数配置
        function removeParameter(paramId) {
            document.getElementById(paramId).remove();
        }
        
        // 验证模板
        async function validateTemplate() {
            const content = document.getElementById('template-content').value;
            
            if (!content.trim()) {
                showNotification('请输入模板内容', 'error');
                return;
            }
            
            try {
                const response = await fetch('/api/prompts/validate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        content: content
                    })
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    const result = data.data;
                    if (result.valid) {
                        showNotification('模板验证通过', 'success');
                    } else {
                        showNotification('模板验证失败: ' + result.errors.join(', '), 'error');
                    }
                } else {
                    showNotification('验证失败: ' + data.message, 'error');
                }
            } catch (error) {
                showNotification('验证失败: ' + error.message, 'error');
            }
        }
        
        // 创建模板
        async function createTemplate(event) {
            event.preventDefault();
            
            const formData = new FormData(event.target);
            const parameters = [];
            
            // 收集参数配置
            document.querySelectorAll('#parameters-list .parameter-config').forEach(paramDiv => {
                const paramData = {
                    name: paramDiv.querySelector('[name="param_name"]').value,
                    param_type: paramDiv.querySelector('[name="param_type"]').value,
                    display_name: paramDiv.querySelector('[name="param_display"]').value,
                    is_required: paramDiv.querySelector('[name="param_required"]').value === 'true',
                    description: paramDiv.querySelector('[name="param_description"]').value,
                    default_value: paramDiv.querySelector('[name="param_default"]').value,
                    ui_component: paramDiv.querySelector('[name="param_ui"]').value,
                    enable_thinking: paramDiv.querySelector('[name="param_thinking"]').checked
                };
                
                if (paramData.name) {
                    parameters.push(paramData);
                }
            });
            
            // 收集深度思考配置
            const enableThinking = document.getElementById('enable-thinking').checked;
            const thinkingConfig = {
                enable_thinking: enableThinking,
                thinking_mode: enableThinking ? document.getElementById('thinking-mode').value : 'auto',
                thinking_prompt: enableThinking ? document.getElementById('thinking-prompt').value : null
            };
            
            const templateData = {
                name: formData.get('template-name'),
                description: formData.get('template-description'),
                category: formData.get('template-category'),
                content: formData.get('template-content'),
                output_format: formData.get('template-format'),
                parameters: parameters,
                ...thinkingConfig
            };
            
            try {
                const response = await fetch('/api/prompts/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(templateData)
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    showNotification('模板创建成功', 'success');
                    event.target.reset();
                    document.getElementById('parameters-list').innerHTML = '';
                    loadTemplates();
                } else {
                    showNotification('创建失败: ' + data.message, 'error');
                }
            } catch (error) {
                showNotification('创建失败: ' + error.message, 'error');
            }
        }
        
        // 渲染模板
        async function renderTemplate() {
            const templateId = document.getElementById('render-template').value;
            
            if (!templateId) {
                showNotification('请选择模板', 'error');
                return;
            }
            
            // 收集参数值
            const parameters = {};
            document.querySelectorAll('#render-parameters input, #render-parameters select').forEach(input => {
                // 处理不同类型的输入值
                if (input.type === 'checkbox') {
                    parameters[input.name] = input.checked;
                } else if (input.type === 'number') {
                    parameters[input.name] = parseFloat(input.value);
                } else {
                    parameters[input.name] = input.value;
                }
            });
            
            // 检查是否有深度思考选项
            const enableThinkingInput = document.getElementById('render-enable-thinking');
            const enableThinking = enableThinkingInput ? enableThinkingInput.checked : false;
            
            try {
                const renderData = {
                    template_id: parseInt(templateId),
                    parameters: parameters
                };
                
                // 如果有深度思考选项，添加到请求中
                if (enableThinkingInput) {
                    renderData.enable_thinking = enableThinking;
                }
                
                const response = await fetch('/api/prompts/render', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(renderData)
                });
                
                const data = await response.json();
                
                if (data.code === 200) {
                    const result = data.data;
                    
                    // 显示渲染结果
                    document.getElementById('render-result').style.display = 'block';
                    let renderOutput = result.rendered_prompt;
                    
                    // 如果有深度思考内容，也显示出来
                    if (result.thinking_content) {
                        renderOutput = `【深度思考】\n${result.thinking_content}\n\n【正式回复】\n${result.rendered_prompt}`;
                    }
                    
                    document.getElementById('rendered-content').textContent = renderOutput;
                    
                    if (result.validation_errors.length > 0) {
                        showNotification('参数验证错误: ' + result.validation_errors.join(', '), 'error');
                    } else {
                        showNotification('渲染成功', 'success');
                    }
                } else {
                    showNotification('渲染失败: ' + data.message, 'error');
                }
            } catch (error) {
                showNotification('渲染失败: ' + error.message, 'error');
            }
        }
        
        // 加载统计数据
        async function loadStats() {
            try {
                const response = await fetch('/api/prompts/');
                const data = await response.json();
                
                if (data.code === 200) {
                    const templates = data.data.items;
                    
                    // 计算统计数据
                    const totalTemplates = templates.length;
                    const totalUsage = templates.reduce((sum, t) => sum + (t.usage_count || 0), 0);
                    
                    document.getElementById('total-templates').textContent = totalTemplates;
                    document.getElementById('total-usage').textContent = totalUsage;
                    document.getElementById('success-rate').textContent = '95%';
                    document.getElementById('avg-time').textContent = '1.2s';
                    
                    // 显示模板统计
                    displayStatsTemplates(templates);
                }
            } catch (error) {
                showNotification('加载统计失败: ' + error.message, 'error');
            }
        }
        
        // 显示模板统计
        function displayStatsTemplates(templates) {
            const container = document.getElementById('stats-templates');
            
            container.innerHTML = templates.map(template => `
                <div class="template-card">
                    <h3>${template.name}</h3>
                    <div class="meta">
                        分类: ${template.category} | 
                        使用次数: ${template.usage_count || 0} | 
                        创建时间: ${new Date(template.created_at).toLocaleDateString()}
                    </div>
                    <div class="actions">
                        <button class="btn btn-primary" onclick="viewStats(${template.id})">查看详情</button>
                    </div>
                </div>
            `).join('');
        }
        
        // 编辑模板（占位函数）
        function editTemplate(id) {
            showNotification('编辑功能开发中', 'error');
        }
        
        // 复制模板（占位函数）
        function duplicateTemplate(id) {
            showNotification('复制功能开发中', 'error');
        }
        
        // 删除模板（占位函数）
        function deleteTemplate(id) {
            if (confirm('确定要删除这个模板吗？')) {
                showNotification('删除功能开发中', 'error');
            }
        }
        
        // 查看统计详情（占位函数）
        function viewStats(id) {
            showNotification('统计详情功能开发中', 'error');
        }
        
        // 模板选择变化时更新参数输入
        document.addEventListener('change', function(event) {
            if (event.target.id === 'render-template') {
                const templateId = event.target.value;
                if (templateId) {
                    updateRenderParameters(templateId);
                } else {
                    document.getElementById('render-parameters').innerHTML = '';
                }
            }
        });
        
        // 更新渲染参数输入
        function updateRenderParameters(templateId) {
            const template = templates.find(t => t.id === parseInt(templateId));
            if (!template || !template.parameters) {
                document.getElementById('render-parameters').innerHTML = '';
                return;
            }
            
            let parametersHtml = '';
            
            // 添加深度思考选项（如果模板支持）
            if (template.enable_thinking) {
                parametersHtml += `
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="render-enable-thinking"> 启用深度思考
                        </label>
                        <small style="color: #666; margin-left: 10px;">
                            ${template.thinking_mode === 'enabled' ? '默认启用' : template.thinking_mode === 'disabled' ? '默认禁用' : '自动模式'}
                        </small>
                    </div>
                `;
            }
            
            // 添加参数输入表格
            parametersHtml += `
                <div class="parameter-config">
                    <h4>参数输入</h4>
                    <table class="parameters-table">
                        <thead>
                            <tr>
                                <th>参数名称</th>
                                <th>参数值</th>
                                <th>说明</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${template.parameters.map(param => `
                                <tr>
                                    <td>
                                        <strong>${param.display_name || param.name}</strong>
                                        ${param.is_required ? '<span style="color: red;">*</span>' : ''}
                                        ${param.enable_thinking ? '<br><small style="color: #007bff;">🧠 深度思考</small>' : ''}
                                    </td>
                                    <td>
                                        ${generateParameterInput(param)}
                                    </td>
                                    <td>
                                        <small style="color: #666;">
                                            ${param.description || ''}
                                            ${param.default_value ? `<br>默认值: ${param.default_value}` : ''}
                                            <br>类型: ${getParamTypeLabel(param.param_type)}
                                        </small>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            `;
            
            document.getElementById('render-parameters').innerHTML = parametersHtml;
        }
        
        // 生成参数输入控件
        function generateParameterInput(param) {
            const name = param.name;
            const required = param.is_required ? 'required' : '';
            const placeholder = param.placeholder || '';
            const defaultValue = param.default_value || '';
            
            switch (param.param_type) {
                case 'boolean':
                    return `
                        <select name="${name}" ${required}>
                            <option value="true" ${defaultValue === 'true' ? 'selected' : ''}>是</option>
                            <option value="false" ${defaultValue === 'false' ? 'selected' : ''}>否</option>
                        </select>
                    `;
                case 'integer':
                    return `<input type="number" name="${name}" placeholder="${placeholder}" value="${defaultValue}" ${required}>`;
                case 'float':
                    return `<input type="number" step="0.01" name="${name}" placeholder="${placeholder}" value="${defaultValue}" ${required}>`;
                case 'array':
                    return `<textarea name="${name}" rows="2" placeholder="请输入数组，用逗号分隔" ${required}>${defaultValue}</textarea>`;
                case 'object':
                    return `<textarea name="${name}" rows="3" placeholder='请输入JSON格式对象，如: {"key": "value"}' ${required}>${defaultValue}</textarea>`;
                default:
                    if (param.ui_component === 'textarea') {
                        return `<textarea name="${name}" rows="3" placeholder="${placeholder}" ${required}>${defaultValue}</textarea>`;
                    } else if (param.ui_component === 'select' && param.enum_values) {
                        const options = param.enum_values.map(val => 
                            `<option value="${val}" ${defaultValue === val ? 'selected' : ''}>${val}</option>`
                        ).join('');
                        return `<select name="${name}" ${required}><option value="">请选择</option>${options}</select>`;
                    } else {
                        return `<input type="text" name="${name}" placeholder="${placeholder}" value="${defaultValue}" ${required}>`;
                    }
            }
        }
        
        // 获取参数类型标签
        function getParamTypeLabel(type) {
            const typeLabels = {
                'string': '字符串',
                'integer': '整数',
                'float': '浮点数',
                'boolean': '布尔值',
                'array': '数组',
                'object': '对象',
                'date': '日期',
                'datetime': '日期时间'
            };
            return typeLabels[type] || type;
        }
    </script>
</body>
</html>